import 'dart:async';

import 'package:event_bus/event_bus.dart';

///@date:  2021/5/18 17:16
///@author:  lixu
///@description:对event_bus进行封装
typedef void EventCallback<T>(T event);

EventBusUtils eventBus = EventBusUtils();

class EventBusUtils {
  static EventBusUtils _instance = EventBusUtils._internal();

  ///初始化eventBus
  EventBus _eventBus = EventBus();

  ///保存订阅的steam
  Map<String, StreamSubscription> _streamMap = {};

  factory EventBusUtils() {
    return _instance;
  }

  EventBusUtils._internal();

  ///开启eventBus订阅
  String on<T>(EventCallback<T> callback) {
    // ignore: cancel_subscriptions
    StreamSubscription stream = _eventBus.on<T>().listen((event) {
      callback(event);
    });

    String eventKey = stream.hashCode.toString();
    _streamMap[eventKey] = stream;
    return eventKey;
  }

  ///发送消息
  void emit(event) {
    _eventBus.fire(event);
  }

  ///移除steam
  ///[eventKey]上面on()方法返回的key，用于在streamMap中获取StreamSubscription,然后调用cancel方法
  void off(String? eventKey) {
    if (eventKey != null) {
      _streamMap[eventKey]?.cancel();
    }
  }
}
